<template>
	<view class="u-wrap u-p-l-30 u-p-r-30">
		<u-form label-width="auto" :rules='rules' :model="addModel" ref="form1">
			<u-form-item label="原密码" prop="oldPassword">
				<u-input type="password" v-model="addModel.oldPassword" />
			</u-form-item>
			<u-form-item label="新密码" prop="password">
				<u-input type="password" v-model="addModel.password" />
			</u-form-item>
			<u-form-item label="确定密码" prop="confirm">
				<u-input type="password" v-model="addModel.confirm" />
			</u-form-item>
		</u-form>
		<u-button @click='commit' :custom-style="customStyle">确定修改</u-button>
	</view>
</template>

<script setup>
	import {
		onReady
	} from '@dcloudio/uni-app';
	import {
		reactive,
		ref
	} from 'vue';
	import {
		updatePassApi
	} from '../../src/api/user.js'
	//表单的ref属性
	const form1 = ref()
	const customStyle = reactive({
		background: '#4BC26A',
		color: '#FFF',
		marginTop: '50px',
		width: '100%'
	})
	//表单绑定的对象
	const addModel = reactive({
		userId:uni.getStorageSync("userId"),
		oldPassword: '',
		password: '',
		confirm: ''
	})
	//表单验证规则
	const rules = reactive({
		oldPassword: [{
			required: true,
			message: '请输入原密码',
			// 可以单个或者同时写两个触发验证方式 
			trigger: ['change', 'blur'],
		}],
		password: [{
			required: true,
			message: '请输入新密码',
			// 可以单个或者同时写两个触发验证方式 
			trigger: ['change', 'blur'],
		}],
		confirm: [{
				required: true,
				message: '请输入确定密码',
				// 可以单个或者同时写两个触发验证方式 
				trigger: ['change', 'blur'],
			},
			{
				validator: (rule, value, callback) => {
					return value == addModel.password;
				},
				message: '新密码和确定密码不一致!'
			},
		]
	})
	//表单提交
	const commit = () => {
		form1.value.validate(async (valid) => {
			if (valid) {
				let res = await updatePassApi(addModel)
				if(res && res.code == 200){
					//清空缓存
					uni.clearStorage()
					//跳转登录
					uni.reLaunch({
						url:"../login/login"
					})
				}
			}
		});
	}
	onReady(() => {
		form1.value.setRules(rules);
	})
</script>

<style>

</style>
